package cn.linstudy.blog.utils;

import cn.linstudy.blog.constant.JwtConstant;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author XiaoLin
 * @Date 2021/12/22 14:27
 * @Description
 */
public class JwtUtils {

    /**
     * 生成Token
     */
    public static String createToken(String userId, String userName) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, JwtConstant.JWT_TTL);
        Date expireDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
            //头
            .withHeader(map)
            .withClaim("userId", userId)
            .withClaim("username", userName)
            .withSubject("令牌")
            //签名时间
            .withIssuedAt(new Date())
            //过期时间
            .withExpiresAt(expireDate)
            //签名
            .sign(Algorithm.HMAC256(JwtConstant.SECRET));
        return token;
    }

    /**
     * 验证Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JwtConstant.SECRET)).build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaims();
    }
}
